﻿using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;

namespace OpenGl.Explore.FirstApp
{
    public class ShaderProgram : OpenglObject, IBindable
    {
        public ShaderProgram()
        {
            _id = GL.CreateProgram();
        }

        public void Attach(ShaderObject shader)
        {
            GL.AttachShader(_id, shader.Id);
        }

        public void Bind()
        {
            GL.UseProgram(_id);
        }

        public void Link()
        {
            GL.LinkProgram(_id);
            GL.GetProgram(_id, GetProgramParameterName.LinkStatus, out int success);
            if(success == 0)
            {
                GL.GetProgramInfoLog(_id, out string info);
                throw new Exception($"Shader Program Link Failed:{info}");
            }
        }

        public void SetUniform(string name, Matrix4 matrix)
        {
            matrix.Transpose();
            var location = GL.GetUniformLocation(_id, name);
            GL.UniformMatrix4(location, false, ref matrix);
        }

        public void Unbind()
        {
            GL.UseProgram(0);
        }

        protected override void Destory()
        {
            GL.DeleteProgram(_id);
        }
    }
}
